//
// Created by yanhai on 2021/3/29.
//

#ifndef CPP_STUDY_SPINLOCK_H
#define CPP_STUDY_SPINLOCK_H

class spinlock {
public:
//    spinlock() {
//        _lock = 0;
//    }
//
//    // nothing to do
//    ~spinlock() {
//        (void) _lock;
//    }

    void lock() {
        while (__sync_lock_test_and_set(&_lock, 1));
    }

    bool try_lock() {
        return __sync_lock_test_and_set(&_lock, 1) == 0;
    }

    void unlock() {
        __sync_lock_release(&_lock);
    }

private:
    int _lock = 0;
};

#endif //CPP_STUDY_SPINLOCK_H
